package com.ruoyi.project.wechatprogram.wxuser.service.impl;

import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.config.service.IConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.wechatprogram.wxuser.mapper.WxUserMapper;
import com.ruoyi.project.wechatprogram.wxuser.domain.WxUser;
import com.ruoyi.project.wechatprogram.wxuser.service.IWxUserService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 员工用户Service业务层处理
 * 
 * @author xinchen
 * @date 2020-04-12
 */
@Service
public class WxUserServiceImpl implements IWxUserService 
{
    private static final Logger log = LoggerFactory.getLogger(WxUserServiceImpl.class);

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private IConfigService configService;
    /**
     * 查询员工用户
     * 
     * @param id 员工用户ID
     * @return 员工用户
     */
    @Override
    public WxUser selectWxUserById(Integer id)
    {
        return wxUserMapper.selectWxUserById(id);
    }

    /**
     * 查询员工用户列表
     *
     * @param wxUser 员工用户
     * @return 员工用户
     */
    @Override
    public List<WxUser> selectWxUserList(WxUser wxUser)
    {
        return wxUserMapper.selectWxUserList(wxUser);
    }

    /**
     * 批量修改员工的余额
     */
    @Override
    @Transactional
    public AjaxResult updateUserBalanceByAll(List<WxUser> userList)
    {
        try {
            Integer resurt =wxUserMapper.updateUserBalanceByAll(userList);
            if (resurt>0){
                return AjaxResult.success("批量增加员工余额成功！");
            }
        }catch (Exception e){
            log.error("批量增加员工余额异常e=！",e);
            throw new BusinessException("批量增加员工余额异常");
        }
        return AjaxResult.error("批量增加员工余额失败！");
    }

    /**
     * 新增员工用户
     * 
     * @param wxUser 员工用户
     * @return 结果
     */
    @Override
    public int insertWxUser(WxUser wxUser)
    {
        if(StrUtil.isBlankIfStr(wxUser.getPassword())){
            String password = configService.selectConfigByKey("sys.user.initPassword");
            wxUser.setPassword(password);
        }
        wxUser.randomSalt();
        wxUser.setPassword(passwordService.encryptPassword(wxUser.getIphone(), wxUser.getPassword(), ""));
        wxUser.setCreateTime(DateUtils.getNowDate());
        wxUser.setCreateBy(ShiroUtils.getLoginName());
        return wxUserMapper.insertWxUser(wxUser);
    }

    /**
     * 根据手机号修改密码
     */
    @Override
    public int updateWxUserPasswordByPhone(WxUser wxUser)
    {
        wxUser.setUpdateTime(DateUtils.getNowDate());
        return wxUserMapper.updateWxUserPasswordByPhone(wxUser);
    }

    /**
     * 修改员工用户
     *
     * @param wxUser 员工用户
     * @return 结果
     */
    @Override
    public int updateWxUser(WxUser wxUser)
    {
        wxUser.setUpdateTime(DateUtils.getNowDate());
        return wxUserMapper.updateWxUser(wxUser);
    }

    /**
     * 修改员工用户金额
     *
     * @param wxUser 员工用户
     * @return 结果
     */
    @Override
    public int updateWxUserBalance(WxUser wxUser)
    {
        wxUser.setUpdateTime(DateUtils.getNowDate());
        return wxUserMapper.updateWxUser(wxUser);
    }

    /**
     * 删除员工用户对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWxUserByIds(String ids)
    {
        return wxUserMapper.deleteWxUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除员工用户信息
     * 
     * @param id 员工用户ID
     * @return 结果
     */
    @Override
    public int deleteWxUserById(Integer id)
    {
        return wxUserMapper.deleteWxUserById(id);
    }

    /**
     * 用户登录查询手机号码是否存在
     *
     * @param wxUser 电话号码
     * @return 员工用户
     */
    @Override
    public WxUser selectWxUserByUser(WxUser wxUser)
    {
        return wxUserMapper.selectWxUserByUser(wxUser);
    }

    /**
     * 导入用户数据
     *
     * @param wxUserList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    @Transactional
    public String importWxUser(List<WxUser> wxUserList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(wxUserList) || wxUserList.size() == 0)
        {
            throw new BusinessException("导入的员工数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (WxUser wxUser : wxUserList)
        {
            try
            {
                // 验证是否存在这个用户
                WxUser u = wxUserMapper.selectWxUserByIphone(wxUser.getIphone());
                if (StringUtils.isNull(u))
                {
                    wxUser.setPassword(password);
                    wxUser.setCreateBy(operName);
                    this.insertWxUser(wxUser);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工：" + wxUser.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    wxUser.setUpdateBy(operName);
                    this.updateWxUser(wxUser);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工：" + wxUser.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工：" + wxUser.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工：" + wxUser.getName() + " 导入失败：";
                failureMsg.append(msg);
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 重置用户密码
     */
    @Override
    public int resetPassword(Integer id)
    {
        WxUser user = new WxUser();
        user.setId(id);
        //先查询此用户
        WxUser user_ord=wxUserMapper.selectWxUserById(id);
        //重置密码为配置项中的默认密码
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(passwordService.encryptPassword(user_ord.getIphone(), password, ""));
        return wxUserMapper.updateWxUser(user);
    }

}
